1, 246, 2, 123, 3, 82, 6, 41 are the divisors of number 246. Squaring these divisors we >get: 1, 60516, 4, 15129, 9, 6724, 36, 1681. The sum of these squares is 84100 which is >290 * 290.
Task
Find all integers between m and n (m and n integers with 1 <= m <= n) such that the sum >of their squared divisors is itself a square.We will return an array of subarrays or of tuples (in C an array of Pair) or a string. >The subarrays (or tuples or Pairs) will have two elements: first the number the squared >divisors of which is a square and then the sum of the squared divisors.
Example:
list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]]
list_squared(42, 250) --> [[42, 2500], [246, 84100]]
The form of the examples may change according to the language, see "Sample Tests".Note
In Fortran - as in any other language - the returned string is not permitted to contain >any redundant trailing whitespace: you can use dynamically allocated character strings.
題目理解:給定一個範圍m~n,範圍中的整數若其所有因數的平方之和,恰為某整數的平方,則回傳此數以及此數所有因數的平方和。
此題可以參考Day4中判斷質數的類似方法來查找某數的因數,應用如下:
import math
def list_squared(m, n):
"""找到範圍中的整數其所有因數平方和,其和恰為某整數的平方"""
result = []
for num in range(m, n + 1):
#因數成對存在故希望一次將成對因數皆收集,但若此因數恰為num的平方根會有重複收集問題,故用set()排除
divisors = set()
#找出num所有的因數,確認是否為因數時可以找到該數的平方根為止
for i in range(1, int(math.sqrt(num)+1)):
if num % i == 0:
divisors.add(i**2)
#因數成對存在,故找到因數後(num/i)會是其另一個因數
divisors.add(int(num/i)**2)
all_sum = sum(divisors)
sr = math.sqrt(all_sum)
#若sr為整數則符合題目要求,故若sr往最下取整去除小數後仍與自己相等,代表sr本身為整數
if sr == math.floor(sr) :
result.append([num, all_sum])
return result